package tmt.usercenter.web.controller.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import tmt.usercenter.web.Application;
import tmt.usercenter.web.domain.TmtAuthority;
import tmt.usercenter.web.domain.security.UserDetailsImpl;
import tmt.usercenter.web.domain.vo.MenuItem;
import tmt.usercenter.web.service.TmtAuthorityService;
import tmt.usercenter.web.utils.HttpServletRequestHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/admin")
@Controller("admin-home-controller")
public class AdminHomeController {

    @Autowired
    private TmtAuthorityService authorityService;

    @RequestMapping({"", "/", "/index"})
    public String home(HttpServletRequest request, Model model,
                       @AuthenticationPrincipal UserDetailsImpl userDetails) {
        List<MenuItem> list = new ArrayList<>();
        try {
            String uri = HttpServletRequestHelper.getValidUriForMenu(request.getContextPath(), request.getRequestURI());

            List<TmtAuthority> tmtAuthorities = authorityService.loadEntities(TmtAuthority.class, "findAuthoritiesByUserId",
                    new Object[]{userDetails.getUserId()}, "1");

            List<TmtAuthority> validAuthorities = tmtAuthorities.stream()
                    .filter(x->Application.SYSTEM_ID.equals(x.getOriginSystem().getClientId()))
                    .collect(Collectors.toList());

            list = TmtAuthority.getValidMenuTree(uri, request.getContextPath(), validAuthorities, Application.SYSTEM_ID,
                    Collections.singletonList(" ADMIN "), null, null);
        } catch (Exception ex) {
        }
        model.addAttribute("menus", list);
        return "admin/index";
    }

    @RequestMapping({"/board"})
    public String board(HttpServletRequest request, Model model) {
        return "admin/board";
    }
}
